package boot.spring.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import boot.spring.realm.UserRealm;

// 小的排前面
@Order(2)
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
	UserRealm realm;
	
	@Autowired
	BCryptPasswordEncoder encoder;
	
	@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(realm).passwordEncoder(encoder);
    }
	
	/**
	 * 放行/oauth认证的URL
	 */
	protected void configure(HttpSecurity http) throws Exception {
		/**
		 http
        .authorizeRequests()
        .antMatchers("/plugins/**","/css/**","/img/**","/js/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")     //登录页面
            .loginProcessingUrl("/loginvalidate") //登录认证地址
            .defaultSuccessUrl("/index", true)  //登陆成功后的地址
            .permitAll()
            .and()
        .logout().logoutUrl("/logout")
            .permitAll()
            .and().csrf().disable();
            **/
		http.antMatcher("/oauth/**").authorizeRequests()
        .antMatchers("/oauth/**").permitAll()
        .and()
        	.formLogin()
	        .loginPage("/login")     //登录页面
	        .loginProcessingUrl("/loginvalidate") //登录认证地址
	        .defaultSuccessUrl("/index", true)  //登陆成功后的地址
	        .permitAll()
        .and().httpBasic() //很重要，不然OAuth2 授权码模式访问/oauth/authorize返回403
        .and().csrf().disable();
	}
	
	//AuthenticationManager对象在OAuth2认证服务中要使用，提取放入IOC容器中
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
	
	public static void main(String[] args) {
	}
}
